﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GOF23.Singleton
{
    /// <summary>
    /// 简单的线程安全版本
    /// 通过一个线程锁保证同一时刻只能有一个线程在执行lock里面的代码，保证只有第一个线程能创建instance实例
    /// 由于lock锁，导致性能下降甚至死锁
    /// </summary>
    public sealed class Singleton2
    {
        private static Singleton2 instance = null;
        private static readonly object obj = new object();
        private Singleton2() { }
        public Singleton2 Instance
        {
            get 
            {
                lock (obj) 
                {
                    if (instance == null)
                    {
                        instance = new Singleton2();
                    }
                    return instance;
                }
            }
        }
    }
}
